<?php

// This class represents a resource item.
//      It has no dependencies, as it only represents a resource class data.
// TODO: Validation for key information automatically.
class folio_resource {

    // Identifying information, uniquely ids any pieces of content, mapping back into Elgg.
    public $item_ident = -1;
    public $item_type = '';
    public $item_owner = -1;

    // Created depending on the type of object.
    public $title = '';
    public $text = '';

    // Create the unique key for an item
    //      It is not wrapped in quotes.
    function encodeKey( $item_ident, $item_type = -999, $userid = -999) {
        if ( $item_type == -999 && $userid == -999 ) {
            return $item_ident->item_ident . ':' . $item_ident->item_type . ':' . $item_ident->item_owner;
        } else {
            return $item_ident . ':' . $item_type . ':' . $userid;
        }
    }

    function handle() {
        return 'folio_decoration' .
            encodeKey( $this->item_ident, $this->item_type, $this->item_owner );
    }

    // Returns an array with the id, type, and userid as keyed values.
    //  Checks for valid ranges.
    function decodeKey( $key ) {
        $KeyArray = explode(":", $key );

        // Validate key's parameters.
        if ( !is_numeric($KeyArray[0]) OR !is_numeric( $KeyArray[2] ) ) {
            trigger_error('ID and userID must be numeric for resource::decodeKey - values '
                    . $KeyArray[0] . ', ' . $KeyArray[2], E_USER_ERROR);
        };

        if( !( $KeyArray[1] == 'blog' || $KeyArray[1] == 'file' || $KeyArray[1] == 'image' )){
            // Error,
            trigger_error('Invalid type: ' . $KeyArray[1] . ' resource::decodeKey', E_USER_ERROR);
        }

        return array( 'id'=>$KeyArray[0], 'type'=>$KeyArray[1], 'userid'=>$KeyArray[2] );
    }

    // Return a link to edit or view a resource
    function getLink( $type ) {

        // Validate
        if ( $type <> 'view' && $type <> 'edit' ) {
            trigger_error("Invalid {$type} type passed to folio_resource::getLink()", E_USER_ERROR);
        }


        $user = folio_user::SelectWhereIdent( $this->item_owner );
        $usename = $user->username;

        // Create the needed link.
        if ( $this->item_type == 'blog' ) {
            if ( $type == 'view' ) {
                return "{$user->username}/weblog/{$this->item_ident}.html";
            } else {
                return "{$user->username}/weblog/edit/{$this->item_ident}";
            }
        } else {
            if ( $type == 'view' ) {
                // Redirect to internal file_redirection page so that we don't have to query the
                //      db for every single file, instead, only needing them for when they're clicked.
                //return "{$username}/files/-9/{$this->item_ident}/image";
                return "mod/folio/html/file_redirection.php?file_ident={$this->item_ident}";
            } else {
                return "mod/file/edit_file.php?edit_file_id=" .
                                "{$this->item_ident}&owner={$this->item_owner}";
            }
        }
    }

//////////////////
//              //
//  SQL Layer   //
//              //
//////////////////

    // Return all items matching the passed criteria.
    //  $key uses params, -1 signifies wildcard in the ID category.
    // @return array with a each matching item.
    function SelectWhereKey( $key ) {
        global $CFG;
        $artifacts = array();

        $Key = folio_resource::decodeKey( $key );

        if ( $Key['type'] == 'blog' ) {
            $artifacts = folio_resource::SelectType_Blog( $key );
        } elseif ( $Key['type'] == 'file' ) {
            $artifacts = folio_resource::SelectType_File( $key, false );
        } elseif ( $Key['type'] == 'image' ) {
            $artifacts = folio_resource::SelectType_File( $key, true );
        } else {
            trigger_error('Invalid value passed to folio_resource::SelectWhereKey ' . $Key['type'], E_USER_ERROR );
        }

        if ( count( $artifacts ) == 0 ) {
            return false;
        } else {
            return $artifacts;
        }
    }

    // Retrieve the keyed blog.
    private function SelectType_Blog( $key ) {
        global $CFG;
        $Key = folio_resource::decodeKey( $key );
        $query = "SELECT b.ident, b.*, u.username FROM {$CFG->prefix}weblog_posts b INNER JOIN {$CFG->prefix}users u ON b.weblog = u.ident WHERE b.weblog = {$Key['userid']}";


        // Option to make the query generic or general
        if ( $Key['id'] != -1 ) {
            $query .= ' AND b.ident = ' . $Key['id'];
        }

        $resources = array();
        $results = recordset_to_array( get_recordset_sql( $query ));

        foreach( $results as $row ) {
            $r = new folio_resource();
            $r->item_ident = intval( $row->ident);
            $r->item_owner = intval( $row->weblog);
            $r->title = $row->title;
            $r->text = $row->body;
            $r->reflection = 'Reflect on this entry';
            $r->item_type = 'blog';

            $resources[] = $r;
        }

        return $resources;
    }

    // Function to load a file.
    private function SelectType_File( $key, $images ) {
        global $CFG;
        $Key = folio_resource::decodeKey( $key );
        $query = "SELECT f.*, u.username FROM {$CFG->prefix}files f INNER JOIN {$CFG->prefix}users u ON f.files_owner = u.ident WHERE files_owner = {$Key['userid']}";

        // Option to make the query generic or general
        if ( $Key['id'] != -1 ) {
            $query .= ' AND f.ident = ' . $Key['id'];
        }

        // Option to include or exclude images.  Msql is not case sensitive.
        $query .= " AND right( f.originalname, 3)" .
                    ($images ? ' ' : ' NOT ') .
                    "IN ( 'jpg', 'BMP', 'GIF', 'pNg', 'GIF' ) ";

        $resources = array();
        //$result = mysql_query( $query );

        //while( $row = mysql_fetch_array( $result, MYSQL_ASSOC )) {

        $results = recordset_to_array( get_recordset_sql( $query ));

        if ( !!$results ) {
            foreach( $results as $row ) {
                $r = new folio_resource();
                $r->item_ident = $row->ident;
                $r->item_type = ($images ? 'image' : 'file');
                $r->item_owner = $row->files_owner;

                // Give a title thru filename if one wasn't specified.
                if ( strlen( $row->title ) < 1 ) {
                    $r->title = $row->originalname;
                } else {
                    $r->title = $row->title;
                }

                $r->text = $row->description;
                $r->reflection = 'Click to reflect on this entry';
                $resources[] = $r;
            }
        }
        return $resources;
    }
}

?>
